// pages/flogin/login.js
import { toGetPhoneNumber } from '../../api/my'
import { toCheckAccountMobile } from '../../api/index'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasUserInfo: false,
    userInfo: {},
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.userInfo) {
      this.setData({
        hasUserInfo: true,
        userInfo: app.globalData.userInfo
      })
    }
  },
  getUserInfo: function (e) {
    let { userInfo } = e.detail;
    if (userInfo) {
      app.globalData.userInfo = userInfo;
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true
      })
    } else {
      wx.showToast({
        title: '授权失败',
        icon: 'none',
        duration: 2000
      })
    }
  },

  getPhoneNumber (e) {
    let _this = this
    if (!!e.detail.encryptedData) {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      toGetPhoneNumber({
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        session_key: app.globalData.session_key
      }).then(res => {
        let { data, success } = res
        if (success) {
          app.globalData.userInfo.phoneNumber = data.phoneNumber
          _this.checkAccountMobile(data.phoneNumber)
        }
      })
    } else {
      wx.showToast({
        title: '授权失败',
        icon: 'none',
        duration: 2000
      })
    }
  },
  checkAccountMobile (phoneNumber) {
    toCheckAccountMobile({
      "openId": app.globalData.openid, //openId
      "mobile": phoneNumber
    }).then(res => {
      wx.hideLoading()
      let { data, success } = res
      if (success && data.id) {
        app.globalData.userInfo = data
        app.globalData.userId = data.id
        app.globalData.phone = data.mobile
        app.globalData.token = data.token
        wx.navigateTo({
          url: `/pages/home/home`
        })
      } else {
        wx.navigateTo({
          url: '/pages/registerinfo/registerinfo'
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (options) {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  goto (e) {
    //console.log(e.target.dataset.url);
    wx.navigateTo({
      url: e.target.dataset.url
    })
  }
})
